<template>
	<view>
		<uni-swipe-action>
			<uni-swipe-action-item @click="onClick" v-for="item in systemList" :key="item.id">
				<uni-list-chat @click="toNewsDetail(item)" clickable :badgeText="item.read ? '' : 'dot'"
					:avatar-circle="true" :title="item.title" :avatar="userUrl" :note="item.content.replace('\n', ' ')"
					:time="item.createdAt"></uni-list-chat>
				<template v-slot:right>
					<view @click="deleteNews(item.id)" class="bg-red-500 text-center text-white flex items-center uni-px-8">
						<text>删除</text>
					</view>
				</template>
			</uni-swipe-action-item>
			<uni-swipe-action-item v-for="item in list" :key="item.id">
				<uni-list-chat clickable @click="toNote(item)" :badgeText="item.read ? '' : 'dot'" :avatar-circle="true"
					:title="item.title" :avatar="item.user.avatar" :note="item.user.name + '：' + item.content"
					:time="item.createdAt"></uni-list-chat>
				<template v-slot:right>
					<view @click="deleteNews(item.id)" class="bg-red-500 text-center text-white flex items-center uni-px-8">
						<text>删除</text>
					</view>
				</template>
			</uni-swipe-action-item>
		</uni-swipe-action>
		<view v-if="systemList.length === 0 && list.length === 0" class="text-center text-gray-400 text-xs uni-my-10">
			还没有收到任何消息</view>
	</view>
</template>
<script>
import {
	httpUserNews,
	httpUserNewsBySystem,
	httpNewsRead,
	httpNewsDelete
} from '@/utils/api.js'
export default {
	data() {
		return {
			userId: '',
			list: [],
			systemList: [],
			userUrl: '../../static/img/user.jpg',
		}
	},
	onLoad() {
		const user = getApp().globalData.user
		this.userId = user.userId || user.id
	},
	mounted() {
		this.getUserNews(this.userId)
		this.getUserNewsBySystem(this.userId)
	},
	async onPullDownRefresh() {
		await this.getUserNews(this.userId)
		await this.getUserNewsBySystem(this.userId)
		uni.stopPullDownRefresh()
	},
	methods: {
		async toNote(news) {
			// 更新已读状态
			const { code } = await httpNewsRead(news.id)
			if (code === 200) {
				uni.navigateTo({
					url: `/pages/note/index?id=${news.noteId}`
				})
			}
		},
		async toNewsDetail(news) {
			const { code } = await httpNewsRead(news.id)
			uni.navigateTo({
				url: `/pages/news/detail?news=${JSON.stringify(news)}`
			})
		},
		async getUserNews(userId) {
			const { code, data } = await httpUserNews(userId)
			if (code === 200) {
				this.list = data
			}
		},
		async getUserNewsBySystem(userId) {
			const { code, data } = await httpUserNewsBySystem(userId)
			if (code === 200) {
				this.systemList = data
			}
		},
		deleteNews(newsId) {
			uni.showActionSheet({
				itemList: ['删除'],
				success: async (res) => {
					const { code } = await httpNewsDelete(newsId)
					if (code === 200) {
						this.getUserNews(this.userId)
						this.getUserNewsBySystem(this.userId)
					}
				},
				fail: function (res) {
					console.log(res.errMsg)
				}
			})
		}
	}
}
</script>
<style lang="scss" scoped>
::v-deep .uni-list--border {
	display: none !important;
}
</style>
